<template>
  <div class="effective-leads-container">
    <!-- 顶部操作栏 -->
    <div class="top-actions-bar">
      <div class="left-section">
        <el-select v-model="searchType" placeholder="按编号" style="width: 100px; margin-right: 8px;">
          <el-option label="按编号" value="number" />
          <el-option label="按姓名" value="name" />
          <el-option label="按电话" value="phone" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="请搜索客户"
          :prefix-icon="Search"
          clearable
          style="width: 200px; margin-right: 12px;"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
      </div>
      
      <div class="right-section">
        <el-button-group>
          <el-button size="small" @click="showAllFilter">全部</el-button>
          <el-dropdown>
            <el-button size="small">
              高级筛选
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showAdvancedFilter">高级筛选</el-dropdown-item>
                <el-dropdown-item @click="showCommonFilter">常用筛选</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-button-group>
        
        <el-button type="primary" size="small" @click="handleDouyinAuth" style="margin-left: 12px;">
          抖音来客授权
        </el-button>
        <el-button size="small" @click="handleCreate">新建</el-button>
        <el-button size="small" @click="handleImport">导入</el-button>
        <el-button size="small" @click="handleImportHistory">导入记录</el-button>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div class="batch-actions-bar">
      <span class="selected-count">已选中 {{ selectedRows.length }} 项</span>
      <div class="batch-buttons">
        <el-button size="small" @click="handleAssignCustomer">分配客户</el-button>
        <el-button size="small" @click="handleAddTag">打标签</el-button>
        <el-button size="small" @click="handleIssueTask">下发任务</el-button>
        <el-button size="small" @click="handleRecycleToPublic">回收到公海</el-button>
        <el-button size="small" @click="handleResourcePoolAssign">资源库分配</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="48" />
        
        <el-table-column prop="name" label="姓名" min-width="180">
          <template #default="{ row }">
            <div class="name-cell">
              <span class="name-text">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="customerType" label="客户类型" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getCustomerTypeTag(row.customerType).type">
              {{ row.customerType }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="assistStage" label="助贷阶段" width="100">
          <template #default="{ row }">
            <span>{{ row.assistStage }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="aiIntentLevel" label="AI意向等级" width="120">
          <template #default="{ row }">
            <span>{{ row.aiIntentLevel || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="expectedAmount" label="期望金额" width="120">
          <template #default="{ row }">
            <span>{{ row.expectedAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="customerSituation" label="客户情况" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.customerSituation }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="infoSource" label="信息来源" width="160">
          <template #default="{ row }">
            <span>{{ row.infoSource }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="marketingSpecialist" label="营销专员" width="120">
          <template #default="{ row }">
            <span>{{ row.marketingSpecialist || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="customerTag" label="客户标签" width="120">
          <template #default="{ row }">
            <span>{{ row.customerTag || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="entryTime" label="录入时间" width="160" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.entryTime }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleRowAction(row)">
              <el-icon><Setting /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 高级筛选对话框 -->
    <el-dialog v-model="advancedFilterVisible" title="高级筛选" width="600px">
      <el-form :model="filterForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户类型">
              <el-select v-model="filterForm.customerType" placeholder="请选择" clearable>
                <el-option label="潜在客户" value="潜在客户" />
                <el-option label="意向客户" value="意向客户" />
                <el-option label="需求客户" value="需求客户" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助贷阶段">
              <el-select v-model="filterForm.assistStage" placeholder="请选择" clearable>
                <el-option label="线索" value="线索" />
                <el-option label="沟通" value="沟通" />
                <el-option label="到店" value="到店" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期望金额">
              <el-select v-model="filterForm.expectedAmount" placeholder="请选择" clearable>
                <el-option label="5~10万元" value="5~10万元" />
                <el-option label="10~30万元" value="10~30万元" />
                <el-option label="30~50万元" value="30~50万元" />
                <el-option label="500~1000万元" value="500~1000万元" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信息来源">
              <el-select v-model="filterForm.infoSource" placeholder="请选择" clearable>
                <el-option label="网络渠道(抖音)" value="网络渠道(抖音)" />
                <el-option label="广告渠道" value="广告渠道" />
                <el-option label="朋友推荐" value="朋友推荐" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="录入时间">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="advancedFilterVisible = false">取消</el-button>
        <el-button type="primary" @click="applyAdvancedFilter">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ArrowDown, Setting } from '@element-plus/icons-vue'
import axios from "axios";

// 响应式数据
const tableRef = ref()
const searchType = ref('number')
const searchKeyword = ref('')
const selectedRows = ref<any[]>([])
const advancedFilterVisible = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选表单
const filterForm = ref({
  customerType: '',
  assistStage: '',
  expectedAmount: '',
  infoSource: '',
  dateRange: null as [Date, Date] | null
})

// 表格数据
const tableData = ref<any[]>([])

// 模拟数据
// const mockData = [
//   {
//     id: '1217195',
//     name: '未命名(1217195)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2025-09-16 14:18:05'
//   },
//   {
//     id: '1217194',
//     name: '线索转发测试(12171...)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2025-09-15 14:07:18'
//   },
//   {
//     id: '1217192',
//     name: '测试王yy (1217192)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '500~1000万元',
//     customerSituation: 'wyy测试',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2025-09-15 11:48:31'
//   },
//   {
//     id: '83780',
//     name: 'H8446 (83780)',
//     customerType: '潜在客户',
//     assistStage: '沟通',
//     aiIntentLevel: '',
//     expectedAmount: '30~50万元',
//     customerSituation: '',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83779',
//     name: 'H8445 (83779)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83778',
//     name: 'H8444 (83778)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83777',
//     name: 'H8443 (83777)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83776',
//     name: 'H8442 (83776)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83775',
//     name: 'H8441 (83775)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   },
//   {
//     id: '83774',
//     name: 'H8440 (83774)',
//     customerType: '潜在客户',
//     assistStage: '线索',
//     aiIntentLevel: '',
//     expectedAmount: '5~10万元',
//     customerSituation: '通过抖音私信添加',
//     infoSource: '网络渠道(抖音)',
//     marketingSpecialist: '',
//     customerTag: '',
//     entryTime: '2024-01-16 13:56:26'
//   }
// ]

// 获取客户类型标签样式
const getCustomerTypeTag = (type: string) => {
  switch (type) {
    case '潜在客户':
      return { type: 'success', text: type }
    case '意向客户':
      return { type: 'warning', text: type }
    case '需求客户':
      return { type: 'info', text: type }
    default:
      return { type: 'info', text: type }
  }
}

// 获取表格数据
const fetchData = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,

    }
    const response = await axios.get('/customers/effective', { params })
    tableData.value = response.data;
    total.value = response.data.total
  }
  catch ( error)
      {
        ElMessage.error('获取客户列表失败')
      }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 显示全部筛选
const showAllFilter = () => {
  // 重置所有筛选条件
  searchKeyword.value = ''
  filterForm.value = {
    customerType: '',
    assistStage: '',
    expectedAmount: '',
    infoSource: '',
    dateRange: null
  }
  currentPage.value = 1
  fetchData()
}

// 显示高级筛选
const showAdvancedFilter = () => {
  advancedFilterVisible.value = true
}

// 显示常用筛选
const showCommonFilter = () => {
  ElMessage.info('常用筛选功能待实现')
}

// 应用高级筛选
const applyAdvancedFilter = () => {
  advancedFilterVisible.value = false
  currentPage.value = 1
  fetchData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 排序处理
const handleSortChange = ({ prop, order }: any) => {
  console.log('排序:', prop, order)
  // 这里可以实现排序逻辑
}

// 批量操作处理
const handleAssignCustomer = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要分配的客户')
    return
  }
  ElMessage.info(`分配客户功能待实现，已选择 ${selectedRows.value.length} 个客户`)
}

const handleAddTag = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要打标签的客户')
    return
  }
  ElMessage.info(`打标签功能待实现，已选择 ${selectedRows.value.length} 个客户`)
}

const handleIssueTask = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要下发任务的客户')
    return
  }
  ElMessage.info(`下发任务功能待实现，已选择 ${selectedRows.value.length} 个客户`)
}

const handleRecycleToPublic = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要回收的客户')
    return
  }
  ElMessageBox.confirm('确定要将选中的客户回收到公海吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`已回收 ${selectedRows.value.length} 个客户到公海`)
    selectedRows.value = []
    fetchData()
  }).catch(() => {})
}

const handleResourcePoolAssign = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要分配的客户')
    return
  }
  ElMessage.info(`资源库分配功能待实现，已选择 ${selectedRows.value.length} 个客户`)
}

// 顶部操作处理
const handleDouyinAuth = () => {
  ElMessage.info('抖音来客授权功能待实现')
}

const handleCreate = () => {
  ElMessage.info('新建客户功能待实现')
}

const handleImport = () => {
  ElMessage.info('导入客户功能待实现')
}

const handleImportHistory = () => {
  ElMessage.info('导入记录功能待实现')
}

// 行操作处理
const handleRowAction = (row: any) => {
  ElMessage.info(`操作客户: ${row.name}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.effective-leads-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .top-actions-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 16px 20px;
    border-radius: 8px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .left-section {
      display: flex;
      align-items: center;
    }

    .right-section {
      display: flex;
      align-items: center;
    }
  }

  .batch-actions-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 12px 20px;
    border-radius: 8px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .selected-count {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }

    .batch-buttons {
      display: flex;
      gap: 8px;
    }
  }

  .table-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;

    .name-cell {
      .name-text {
        font-weight: 500;
        color: #303133;
      }
    }

    .pagination-container {
      display: flex;
      justify-content: flex-end;
      padding: 16px 0 4px;
      margin-top: 16px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .effective-leads-container {
    .top-actions-bar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .left-section,
      .right-section {
        justify-content: center;
      }
    }
  }
}

@media (max-width: 768px) {
  .effective-leads-container {
    padding: 12px;

    .top-actions-bar {
      .left-section,
      .right-section {
        flex-wrap: wrap;
        gap: 8px;
      }
    }

    .batch-actions-bar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .batch-buttons {
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
}
</style>
